package cn.xttc.edu.controller;

import cn.xttc.edu.handler.MyMessageHandler;
import com.soecode.wxtools.api.IService;
import com.soecode.wxtools.api.WxMessageRouter;
import com.soecode.wxtools.api.WxService;
import com.soecode.wxtools.bean.WxXmlMessage;
import com.soecode.wxtools.bean.WxXmlOutMessage;
import com.soecode.wxtools.util.xml.XStreamTransformer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 微信客户端控制器
 *
 * @author yl
 */
@RestController
@RequestMapping("/wx")
public class WxController {

    private final IService iService = new WxService();

    /**
     * 接入微信公众平台
     *
     * @param signature 微信加密签名
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param echostr   随机字符串
     * @return echostr 参数内容
     */
    @GetMapping
    public String check(String signature, String timestamp, String nonce, String echostr) {
        if (iService.checkSignature(signature, timestamp, nonce, echostr)) {
            return echostr;
        }
        return null;
    }

    /**
     * 处理用户在公众号发送消息
     * @param request request
     * @param response response
     * @throws IOException exception
     */
    @PostMapping
    public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        // 创建一个路由器
        try (PrintWriter out = response.getWriter()) {
            WxMessageRouter router = new WxMessageRouter(iService);
            // 微信服务器推送过来的是XML格式。
            WxXmlMessage wx = XStreamTransformer.fromXml(WxXmlMessage.class, request.getInputStream());
            router.rule().handler(new MyMessageHandler()).end();
            // 把消息传递给路由器进行处理，得到最后一个handler处理的结果
            WxXmlOutMessage xmlOutMsg = router.route(wx);
            if (xmlOutMsg != null) {
                out.print(xmlOutMsg.toXml());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
